
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_image_picker/form_builder_image_picker.dart';

class GetPhoto extends StatefulWidget {
  // 传入参数
  const GetPhoto({
    Key? key,
    this.title = '图片选择', // 高度
    this.max = 1,
    this.cameraLabel = '相机',
    this.galleryLabel = '相册',
    this.camera = true ,
    this.gallery = true ,
    required this.other,
    required this.values,
  }) : super(key: key,);
  final String title;
  final int max;
  final String cameraLabel;
  final String galleryLabel;
  final bool camera;
  final bool gallery;
  final Widget other;
  final ValueChanged<String> values;

  @override
  State<StatefulWidget> createState() => GetPhotoState();

}

class GetPhotoState extends State<GetPhoto> {
  final GlobalKey<FormBuilderState> _formKey = GlobalKey<FormBuilderState>();

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        widget.other,
        FormBuilder(
            key: _formKey,
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Container(
                    alignment: Alignment.bottomCenter,//设置控件内容的位置
                    padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
                    child: FormBuilderImagePicker(
                      name: 'photos',
                      maxImages: widget.max,
                      onChanged:(val){
                        if (widget.max == 1) {
                          if(_formKey.currentState!.saveAndValidate()){
                            List Imgs = _formKey.currentState!.value['photos'];
                            if (Imgs.isNotEmpty) {
                              widget.values(Imgs[0].path);
                            }

                          }
                        }
                      },
                      decoration: InputDecoration(
                        labelText: widget.title,
                        border: const OutlineInputBorder(),
                      ),
                      cameraLabel: widget.camera? Text( widget.cameraLabel):Container(),
                      galleryLabel: widget.gallery?Text(widget.galleryLabel):Container(),
                    ),
                  ),
                ]
            )
        ),
      ],
    );
  }


}